using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Collections;
using System.Resources;
using System.Threading;
using System.Reflection;


namespace Rally_Dekstop
{

    public enum VisibleFormType {DEFECT_VIEWER,
                                 EXECUTE_TEST_CASE,
                                 GET_TEST_CASE,
                                 DEFECT_SETTINGS,
                                 TASK_VIEWER,
                                 TEST_CASE_VIEWER}
   
    public partial class RallyDesk : Form
    {
//GLOBALS
        static public string HOSTNAME = null;
        static public string Username = null;
        static public string Password = null;
        static public string msConn = null;
        static public ArrayList WORKSPACENAMES = new ArrayList();
        static public ArrayList WORKSPACEREFERENCES = new ArrayList();
        static public string url = null;       
        static public string CacheKey;
        static public WorkSpace CURRENTWORKSPACE = new WorkSpace();
        private ResourceManager m_ResourceManager = Localizer.getInstance().GetResourceManager();
        static public CacheManager Cache = new CacheManager();
        static public string MainAssemblyPath = null;
        static public string HelpPath = null;

        // This is to maintain  the defect filter settings through out the session.
        static public string DefectQueryString = string.Empty;
        static public string DefectFilterUsername = string.Empty;
        static public string DefectFilterUsernameOperator = string.Empty;
        static public string DefectFilterState = string.Empty;
        static public string DefectFilterStateOperator = string.Empty;
//GLOBALS        

        private int childFormNumber = 0;
        private LoginForm login = null;
        
       

        public RallyDesk()
        {
            InitializeComponent();
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            SetFilePaths();
            
        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            MessageBox.Show((e.ExceptionObject as Exception).Message, "Rally Desk", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.Message, "Rally Desk",MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public void EnableDisbaleMenuItems(bool enable)
        {
            this.settingsToolStripMenuItem.Enabled = this.viewDefectsToolStripMenuItem.Enabled =
            this.testCaseExecutionToolStripMenuItem.Enabled = this.createTestCasesToolStripMenuItem.Enabled = enable;
        }

        private void ShowNewForm(object sender, EventArgs e)
        {
            // Create a new instance of the child form.
            Form childForm = new Form();
            // Make it a child of this MDI form before showing it.
            childForm.MdiParent = this;
            childForm.Text = "Window " + childFormNumber++;
            childForm.Show();
        }

        private void SetFilePaths()
        {
            string AssemblyPath;
            Assembly assembly = Assembly.GetExecutingAssembly();
            AssemblyPath = (assembly.Location);
            MainAssemblyPath = AssemblyPath.Substring(0, AssemblyPath.Length - 17);
            
            StringBuilder HelpPathStr = new StringBuilder();
            HelpPathStr.Append(MainAssemblyPath);
            HelpPathStr.Append("Resources\\rallydesktop.chm");
            HelpPath = HelpPathStr.ToString();
        }

        private void OpenFile(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = openFileDialog.FileName;
                // TODO: Add code here to open the file.
            }
        }

        private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = saveFileDialog.FileName;
                // TODO: Add code here to save the current contents of the form to a file.
            }
        }

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void CutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard to insert the selected text or images into the clipboard
        }

        private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard to insert the selected text or images into the clipboard
        }

        private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard.GetText() or System.Windows.Forms.GetData to retrieve information from the clipboard.
        }

        //private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    toolStrip.Visible = toolBarToolStripMenuItem.Checked;
        //}

        //private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    statusStrip.Visible = statusBarToolStripMenuItem.Checked;
        //}

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }

        private void loginToRallyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {

                if (loginToRallyToolStripMenuItem.Text == "Login to Rally")
                {
                   
                    if (login == null)
                        login = new LoginForm(this);
                    if (CURRENTWORKSPACE == null)
                        CURRENTWORKSPACE = new WorkSpace();

                    login.SetStatusOfForm(true);

                    login.ShowDialog();
                    if (Username != null && Password != null)
                    {
                        loginToRallyToolStripMenuItem.Text = "Logout";
                        QA_Options_ToolStripMenuItem.Enabled = true;
                        defectsToolStripMenuItem.Enabled = true;
                        tasksToolStripMenuItem.Enabled = true;
                        DefectQueryString = "(Owner = \"" + RallyDesk.Username + "\")";
                        DefectFilterUsername = RallyDesk.Username;
                        DefectFilterUsernameOperator = "=";
                        DefectFilterState = "All";
                        DefectFilterStateOperator = "=";





                        
                        CacheKey = RallyDesk.Username + RallyDesk.Password + RallyDesk.HOSTNAME;
                        
                       if (WORKSPACENAMES.Count == 1)
                        {
                            this.Cursor = Cursors.WaitCursor;
                            toolStripStatusLabel.Text = "Selecting Workspace...";
                            ProgressBarMain.Style = ProgressBarStyle.Marquee;
                            ProgressBarMain.Visible = true;
                            Utilities.SelectWork((string)WORKSPACENAMES[0], 0);
                            Utilities.SetProjects();
                           
                            ProgressBarMain.Visible = false;
                            toolStripStatusLabel.Text = "Ready"; 
                          
                            this.Cursor = Cursors.Default;
                        }
                        else
                        {
                            this.changeWorkspaceToolStripMenuItem.Enabled = true;
                            this.changeWorkspaceToolStripMenuItem.PerformClick();
                        }
                        

                        
                                   
                    }

                  
                }
                else
                {
                   
                    if (this.MdiChildren.Length > 0)
                    {
                        DialogResult res = new DialogResult();
                        res = MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/LogoutWarning"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (res == DialogResult.No)
                            return;
                        else
                        {
                            foreach (Form fm in this.MdiChildren)
                            {
                                fm.Close();
                            }
                        
                        }
                    }
                    if(this.MdiChildren.Length == 0)
                    {
                        Utilities.ClearAllRallyDeskInfo();
                        
                        this.changeWorkspaceToolStripMenuItem.Enabled = false;
                        loginToRallyToolStripMenuItem.Text = "Login to Rally";
                        QA_Options_ToolStripMenuItem.Enabled = false;
                        defectsToolStripMenuItem.Enabled = false;
                        tasksToolStripMenuItem.Enabled = false;
                        reportsToolStripMenuItem.Enabled = false;
                        DefectQueryString = string.Empty;
                        DefectFilterUsername = string.Empty;
                        DefectFilterUsernameOperator = string.Empty;
                        DefectFilterState = string.Empty;
                        DefectFilterStateOperator = string.Empty;
                       
                    }
               }
            }
            catch (System.Net.WebException ex)
            {
                if ((ex.Status.Equals(System.Net.WebExceptionStatus.ConnectFailure)))
                {
                    MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/login/ConnectFailure"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    login.Close();
                    login = null;
                    return;
                }
                else
                    if ((ex.Status.Equals(System.Net.WebExceptionStatus.NameResolutionFailure)))
                    {
                        MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/login/InternetAccess"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        login.Close();
                        login = null;
                        return;
                    }
                    else
                        throw;
            }
            catch (Exception)
            {
            }
            finally
            {
                
            }
            

        }

        
       private void RallyDesk_Load(object sender, EventArgs e)
       {
           loginToRallyToolStripMenuItem.PerformClick();
       }

       private void helpMenu_Click(object sender, EventArgs e)
       {

       }

       private void uploadTestResultsToolStripMenuItem_Click(object sender, EventArgs e)
       {
       }

       private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
       {
           
           About abt = new About();
           //abt.MdiParent = this;
           abt.ShowDialog();
       }

       private void getTemplateToolStripMenuItem_Click(object sender, EventArgs e)
       {
           //MessageBox.Show("The Template can be found in the installed directory. It can also be accessed by the Program Menu","Rally Desk");
       }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void getTestCaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmFetchTestCases GetSRTests = new frmFetchTestCases(this);
            GetSRTests.Show();
        }

        private void uploadTestResultsToolStripMenuItem1_Click(object sender, EventArgs e)
        {

            
        }

        private void fileMenu_Click(object sender, EventArgs e)
        {

        }

        private void createTestCasesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Utilities.GetWorkspaceSpecifics("TestCase");
            CreateTestCase tc = new CreateTestCase();
            tc.Show();
        }

        private void changeWorkspaceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.MdiChildren.Length > 0)
            {
                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/WorkspaceChangeWarning"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            
            WorkspaceSelector WorkSel = new WorkspaceSelector(this);
            WorkSel.ShowDialog();
            

        }

        private void cmb_projects_SelectedIndexChanged(object sender, EventArgs e)
        {
            RallyDesk.CURRENTWORKSPACE.SelectedProject = Rally_Dekstop.Program.RallyMain.cmb_projects.Text;
            RallyDesk.CURRENTWORKSPACE.SelectedProjectRef = ((string)RallyDesk.CURRENTWORKSPACE.Projects.ProjectRef[Rally_Dekstop.Program.RallyMain.cmb_projects.SelectedIndex]);
        }

        private void cmb_projects_SelectedValueChanged(object sender, EventArgs e)
        {
            RallyDesk.CURRENTWORKSPACE.SelectedProject = Rally_Dekstop.Program.RallyMain.cmb_projects.Text;
            RallyDesk.CURRENTWORKSPACE.SelectedProjectRef = ((string)RallyDesk.CURRENTWORKSPACE.Projects.ProjectRef[Rally_Dekstop.Program.RallyMain.cmb_projects.SelectedIndex]);
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void RallyDesk_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if(RTFConvertor.Convertor.isWordOpen())
            //RTFConvertor.Convertor.CloseWordInstance();
        }

        private void getExecutionTemplateToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (this.GetVisibleObjectCount(VisibleFormType.TEST_CASE_VIEWER) > 0)
                return;
            this.getExecutionTemplateToolStripMenuItem.Enabled = false;
            try
            {
                frmFetchTestCases GetSRTests = new frmFetchTestCases(this);
                GetSRTests.Show();
            }
            finally
            {
                this.getExecutionTemplateToolStripMenuItem.Enabled = true;
            }
        }

        private void executeTestCasesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Utilities.GetWorkspaceSpecifics("TestResult");
            string FileName;
            try
            {

                int count = 0;

                OpenFileDialog op1 = new OpenFileDialog();
                op1.DefaultExt = ".xls";
                op1.Filter = "Excel(*.xls)|*.xls";

                //toolStripStatusLabel.Text = "Uploading test results";

                if (op1.ShowDialog() == DialogResult.OK)
                {
                    FileName = op1.FileName;
                    op1.Dispose();
                    msConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + FileName + ";" + "Extended Properties=\"Excel 8.0;HDR=YES\"";

                    frmTestCaseExecution NewData = new frmTestCaseExecution();
                    OleDbConnection conn = new OleDbConnection();
                    conn.ConnectionString = msConn;
                    conn.Open();

                    System.Data.OleDb.OleDbCommand cmd = new OleDbCommand("Select * From [test$]", conn);
                    OleDbDataReader rdr = cmd.ExecuteReader();
                    System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem();
                    string[] NewItem ={ "", "", "", "", "", "" };


                    while (rdr.Read())
                    {

                        if (rdr.GetValue(0) != System.DBNull.Value)
                            NewItem[0] = (rdr.GetString(0));
                        else
                            NewItem[0] = "";

                        if (rdr.GetValue(1) != System.DBNull.Value)
                            NewItem[1] = (rdr.GetString(1));
                        else
                            NewItem[1] = "";


                        if (rdr.GetValue(2) != System.DBNull.Value)
                            NewItem[2] = (rdr.GetString(2));
                        else
                            NewItem[2] = "";

                        if (rdr.GetValue(3) != System.DBNull.Value)
                            NewItem[3] = (rdr.GetString(3));
                        else
                            NewItem[3] = "";

                        if (rdr.GetValue(4) != System.DBNull.Value)
                            NewItem[4] = (rdr.GetString(4));
                        else
                            NewItem[4] = "";
                        if (rdr.GetValue(5) != System.DBNull.Value)
                            NewItem[5] = (rdr.GetString(5));
                        else
                            NewItem[5] = "";

                        listViewItem1 = new System.Windows.Forms.ListViewItem(NewItem, -1);
                        NewData.listView_testresults.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
            listViewItem1});
                        count++;


                    }
                    rdr.Close();
                    conn.Close();
                    msConn = null;
                    NewData.RecNum_label.Text = Convert.ToString(count);

                    NewData.Text = "Create Test Results-[" + FileName + "]";
                    NewData.filename = FileName;
                    NewData.listView_testresults.Sorting = SortOrder.Ascending;
                    NewData.Show();


                }
            }
            catch (System.IndexOutOfRangeException)
            {

                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/InvalidTemplate"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.Data.OleDb.OleDbException)
            {

                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/InvalidTemplate"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            catch (Exception)
            {
                throw;
            }
        }

       
        private void viewDefectsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.GetVisibleObjectCount(VisibleFormType.DEFECT_VIEWER) > 0)
                return;
            Rally_Dekstop.Program.RallyMain.viewDefectsToolStripMenuItem.Enabled = false;
            try
            {
                Utilities.GetWorkspaceSpecifics("Defect");
                frmDefectViewer guiDefectViewer = new frmDefectViewer(this);

                guiDefectViewer.ClearForm();

                guiDefectViewer.ClearDefectData();
                guiDefectViewer.Show();
            }
            finally
            {
                Rally_Dekstop.Program.RallyMain.viewDefectsToolStripMenuItem.Enabled = true;
            }
      
        }

        private void cacheDefectstoolStripMenu_Click(object sender, EventArgs e)
        {
            
        }

        private void viewTasksToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.GetVisibleObjectCount(VisibleFormType.TASK_VIEWER) > 0)
                return;

            Utilities.GetWorkspaceSpecifics("Task");
            GUITasksViewer guiTasksViewer = new GUITasksViewer(this);
            guiTasksViewer.Show();
        }

        private void defectReportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IRallyService service = null;
            if (RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceType == "UseCase")
            {
                service = new RallyAPIUseCase(RallyDesk.url);
            }
            else
            {
                service = new RallyAPIUserStory(RallyDesk.url);
            }

            string year = "2008";
            string month = "02";
            string day = "10";
            int result = service.ReturnNumberOfDefectsReOpened(Utilities.CovertToRallyTimeStamp(year, month, day));

            MessageBox.Show("Total Number of Defects ReOpened by you are : " + Convert.ToString(result));
            result = service.ReturnNumberOfDefectsReported(Utilities.CovertToRallyTimeStamp(year, month, day));

            MessageBox.Show("Total Number of Defects Logged by you are : " + Convert.ToString(result));
           
        }

        private void helpTopicsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                System.Windows.Forms.Help.ShowHelp(this, HelpPath, HelpNavigator.TableOfContents);
            }
            catch (Exception ee)
            {
                throw;
            }
                    
            
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Rally_Dekstop.Program.RallyMain.settingsToolStripMenuItem.Enabled = false;
            try
            {
                Utilities.GetWorkspaceSpecifics("Defect");
                DefectFilterSelector DefSec = new DefectFilterSelector();

                DefSec.ShowDialog();
                if (DefSec.ShowResults)
                {
                    this.settingsToolStripMenuItem.Enabled = false;
                    this.viewDefectsToolStripMenuItem.PerformClick();
                }
            }
            finally 
            {
                Rally_Dekstop.Program.RallyMain.settingsToolStripMenuItem.Enabled = true;
            }
           
        }

        public int GetVisibleObjectCount(VisibleFormType visibleFormType)
        {
            int result = 0;

            foreach (Form fm in this.MdiChildren)
            {
                if (fm.Tag != null)
                {
                    if (((VisibleFormType)fm.Tag) == visibleFormType)
                    {
                        result++;
                    }
                }
            }

            return result;
        }

        private void testCaseExecutionToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void editTestCasesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Utilities.GetWorkspaceSpecifics("TestCase");
            frmReviewEditTestCases tc = new frmReviewEditTestCases(this);
            tc.Show();
        }
   
   }
}
